#include "roledelete.h"
#include "ui_roledelete.h"
#include <QMessageBox>
#include "msgbox.h"
#include "userlogger.h"

RoleDelete::RoleDelete(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::RoleDelete)
{
    ui->setupUi(this);
    bdf = BllDataFlow::getInstance();
    sqlHelper = SqlHelper::getInstance();

    //Signals and Slots
    connect(bdf, &BllDataFlow::sendDeletedRoleSignal, this, &RoleDelete::setRole);
    connect(bdf, &BllDataFlow::retranslateUiSignal, this, &RoleDelete::retranslateUiSlot);

    initWidget();
}

RoleDelete::~RoleDelete()
{
    delete ui;
}

void RoleDelete::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    painter.fillRect(this->rect(), QColor(255, 255, 255, 0));
}

void RoleDelete::on_btnClose_clicked()
{
    this->hide();
}

void RoleDelete::retranslateUiSlot()
{
    ui->retranslateUi(this);
}

void RoleDelete::on_btnConfirmDeleteRole_clicked()
{
    EttaError ret = sqlHelper->deleteRole(role);
    if (ret == EttaError::OK)
    {
        ret = sqlHelper->updateUserPermission2Zero(role);
    }

    if (ret == EttaError::OK)
    {
        QString message = QString("%1: %2").arg(tr("Delete Role")).arg(role.name);
        UserLogger::log(message);
        bdf->showAllRoles();
        this->hide();
    }
    else
    {
        UserLogger::error(QString(tr("Failed to Delete Role %1")).arg(role.name));
        QString result = (ret == EttaError::OK) ? tr("Success") : tr("Failed");
        MsgBox::information(this, tr("Delete Role").arg(role.name), QString(tr("%1 to Delete Role")).arg(result));
    }
}

void RoleDelete::on_btnCancel_clicked()
{
    this->hide();
}

void RoleDelete::setRole(Role role_)
{
    role = role_;
    bool state = sqlHelper->checkRoleHasUser(role.name);
    if(state)
    {
        MsgBox::information(this, QString(tr("Role")), QString(tr("There are users under this role!")));
        this->hide();
    }
    else
    {
        this->show();
    }
}

void RoleDelete::initWidget()
{
    setAttribute(Qt::WA_TranslucentBackground, true);
    QGraphicsDropShadowEffect *shadow = new QGraphicsDropShadowEffect();
    shadow->setColor(QColor(0,0,0,150));
    shadow->setOffset(1, 1);
    shadow->setBlurRadius(16);
    ui->widget->setGraphicsEffect(shadow);
    role = initRole();
//    this->setProperty("form", true);
//    this->setProperty("canMove", true);
//    this->setWindowFlags(Qt::FramelessWindowHint | Qt::WindowSystemMenuHint | Qt::WindowMinMaxButtonsHint);

}
